import json

import datetime
from django.http import JsonResponse
from rest_framework import generics
from .seralizers import *
from .filters import *


def task_create(request):
    res = {"code": 400, "message": "", "data": None}
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            now = datetime.datetime.today()
            today = now.strftime("%Y-%m-%d %H:%M:%S")
            data['time'] = today
            Task.objects.create(**data)
            res['code'] = 200
            res['message'] = '新增成功'
        except Exception as e:
            res['code'] = 500
            res['message'] = '服务器错误：'+str(e)
    else:
        res['message'] = '请使用POST方法'
    return JsonResponse(res)


# Retrieve task list
class TasksView(generics.ListAPIView):
    queryset = Task.objects.all().order_by('id')
    serializer_class = TaskListSerializer
    filterset_class = TaskFilter


def task_detail(request, pk):
    # ip = ''
    # if request.META.get('HTTP_X_FORWARDED_FOR'):
    #     ip = request.META.get('HTTP_X_FORWARDED_FOR')
    # else:
    #     ip = request.META.get('REMOTE_ADDR')
    # # 当有多级代理时，HTTP_X_FORWARDED_FOR返回多个IP，取第一个即可。
    # print('*&&&', ip)
    res = {"code": 400, "message": "", "data": None}
    if request.method == 'GET':
        try:
            # data1 = serializers.serialize("json",Task.objects.all())
            # print(data1)
            instance = Task.objects.get(id=pk)

            data = TaskIDSerializer(instance=instance)
            res['data'] = data.data
            res['code'] = 200
            res['message'] = '操作成功'
        except Exception as e:
            res['code'] = 500
            res['message'] = '服务器错误：' + str(e)
    else:
        res['message'] = '请使用GET方法'
    return JsonResponse(res)


def task_update(request, pk):
    # 从url里获取单个任务的pk值，然后查询数据库获得单个对象实例
    res = {"code": 400, "message": "", "data": None}
    if request.method == 'PUT':
        try:
            data = json.loads(request.body)
            now = datetime.datetime.today()
            today = now.strftime("%Y-%m-%d %H:%M:%S")
            data['time'] = today
            Task.objects.filter(id=pk).update(**data)
            res['code'] = 200
            res['message'] = '编辑成功'
        except Exception as e:
            res['code'] = 500
            res['message'] = '服务器错误：' + str(e)
    else:
        res['message'] = '请使用PUT方法'
    return JsonResponse(res)


# Delete a single task
def task_delete(request, pk):
    # 从url里获取单个任务的pk值，然后查询数据库获得单个对象实例
    res = {"code": 400, "message": "", "data": None}
    if request.method == 'DELETE':
        try:
            Task.objects.filter(id=pk).delete()
            res['code'] = 200
            res['message'] = '删除成功'
        except Exception as e:
            res['code'] = 500
            res['message'] = '服务器错误：' + str(e)
    else:
        res['message'] = '请使用DELETE方法'
    return JsonResponse(res)
